<?php
//catalogus functionaliteit //iTsOc
namespace ITSociaal\Wordpress\Themes\EnfoldChild\Shopp;
?>


<?php
error_reporting(~0);

/**
 * Return first element of given array
 *
 * @param array $array
 *
 * @return mixed Value of first element
 */
function first($array) {
	return array_values($array)[0];
}

/**
 * Query a DOMDocument with XPath
 *
 * @param \DOMDocument $doc
 * @param string       $query
 *
 * @return \DOMNode[]   Query results or empty array
 */
function qxpath(\DOMDocument $doc, $query) {
	return iterator_to_array(
		(new \DOMXPath($doc))->query($query)
	);
}

/**
 * Parse a given HTML fragment into a DOMDocument
 *
 * @param string $html Valid HTML
 *
 * @return \DOMDocument
 */
function html2dom($html) {
	return \DOMDocument::loadHTML(
		'<?xml version="1.1" encoding="utf-8" ?>' . "\n" .
		$html,
		0
		|LIBXML_NONET
		|LIBXML_NOWARNING
		|LIBXML_NOERROR
		//|LIBXML_HTML_NOIMPLIED//does not work
		|LIBXML_HTML_NODEFDTD
	);
}

// shopp( 'storefront.catalog-products' ) does not include a list
// of categories. There oughta be an easier way to fix this thing.
print(call_user_func_array(
	function(\DOMDocument $dCatalog) {
		// bookkeeping :P
		$bPrev = libxml_use_internal_errors(true);

		// Get main category element
		$elRoot = first(qxpath($dCatalog, '//*[@class="category"][1]'));

		// Generate list of categories
		$sCategoriesHtml = shopp('storefront', 'category-list', [
			// Add div tag for later retrieval
			'after' => '</div>',
			'before' =>
				'<div class="custom-category-list">',

			'hierarchy' => true,
			'products' => true,
			'return' => 'true', // why the fuck is this not default?
			//'title' => 'Producten menu',
		]);

		// XPath to find navigation element
		$sNavXpath = '//section[contains(@class, "navigation")][1]';

		// Manipulate the DOM
		first(qxpath($dCatalog, $sNavXpath))
			->insertBefore(
				$dCatalog->importNode(
					first(qxpath(
						html2dom($sCategoriesHtml),
						// Find the above div tag
						"//div[1]"
					)),
					true
				),
				first(qxpath(
					$dCatalog,
					$sNavXpath . '//*[@id="shopp-catalog-orderby-menu"]/..'
				))
			);

		libxml_use_internal_errors($bPrev);

		return $dCatalog->saveHTML($elRoot);
	},
	[
		// Original catalog html
		html2dom(shopp( 'storefront', 'catalog-products', [
			"controls" => true,
			"return" => true,
		])),
	]
));

/* vi:set ts=4 sw=4 noet: */
